package com.longxi.tianjintianbao.ui.presenter.patrol;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.RadioGroup;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataPatrolController;
import com.longxi.tianjintianbao.greedao.entity.Patrol;
import com.longxi.tianjintianbao.model.completeEnter.PicturesPath;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.patrol.IEditPatrolResultsAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetworkUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class EditPatrolResultsAtPresenter extends BasePresenter<IEditPatrolResultsAtView> {

    private String ENTEREDITTEXT = "";
    private List<PicturesPath> SELECTPIC = new ArrayList<>();
    private String SELECTSTATE = "正常";//1正常 0异常

    public EditPatrolResultsAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("编辑巡检结果");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setTvRight("保存");
    }

    public void initListener() {
        getView().getRadioGroup().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.rBtnNormal){
                    SELECTSTATE = "正常";
                }else{
                    SELECTSTATE = "异常";
                }
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                addPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                SELECTPIC.clear();
                for (LocalMedia media : addPicUtils.selectList) {
                    SELECTPIC.add(new PicturesPath(media.getCompressPath()));
                }
                gridImageAdapter.setList(addPicUtils.selectList);
                gridImageAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void detachView() {
        super.detachView();
    }

    public void onClickSaveBtn() {

        ENTEREDITTEXT = getView().getEtContent().getText().toString().trim();

        if(SELECTSTATE.equals("异常")){
            if(TextUtils.isEmpty(ENTEREDITTEXT)){
                MyUtils.showToast("请输入说明");
                return;
            }

            if(SELECTPIC.size() == 0){
                MyUtils.showToast("请选择图片");
                return;
            }
        }

        saveInspection();
    }

    /**
     * 如果网络正常直接上传
     * 如果网络不正常 先保存在本地
     */
    public void saveInspection() {
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        String image1 = "";
        String image2 = "";
        for (int i = 0; i < addPicUtils.selectList.size(); i++) {
            if(i == 0){
                image1 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }else if(i == 1){
                image2 = MyUtils.imageToBase64(addPicUtils.selectList.get(i).getCompressPath());
            }
        }

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
            object.put("billdetailid", mContext.getIntent().getStringExtra(AppConst.BILLDETAILID));
            object.put("state", SELECTSTATE);
            object.put("explain", ENTEREDITTEXT);
            object.put("image1", image1);
            object.put("image2", image2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveInspection2(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }

                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }
}
